/**
 * Created by wang on 2015-10-22.
 * 随机数字键盘
 */
define(['angular'], function (angular) {
    "use strict";

    var directive = function ($parse, $log) {
        return {
            restrict: "A",
            scope: {
                password: '=digitalKeyboard'
            },
            link: function( scope, element, attrs) {

                if(attrs.digitalKeyboard == "false") {
                    element.bind("click", function() {
                        if(typeof DigitalKeyboard !== 'undefined') {
                            DigitalKeyboard.close(function(status){
                                if(scope.$parent.selectDigitalKeyboardElement){
                                    scope.$parent.selectDigitalKeyboardElement.removeClass("keypad");
                                }
                            });
                        }
                    });
                } else {
//                    var getter = $parse(attrs.ngModel);
//                    var setter = getter.assign;
                    if(typeof cordova !== 'undefined' && typeof DigitalKeyboard !== 'undefined') {
                        element.attr("readonly", "readonly");
                        element.bind("click", function() {
                            if(scope.$parent.selectDigitalKeyboardElement){
                                scope.$parent.selectDigitalKeyboardElement.removeClass("keypad");
                            }
                            element.parent().parent().addClass("keypad");
                            scope.$parent.selectDigitalKeyboardElement  = element.parent().parent();
                            cordova.plugins.Keyboard.close();
                            DigitalKeyboard.active({"length":6, "text": scope.password}, function(obj){
                                scope.$apply(function() {
                                    scope.password = obj.text;
                                });
                                if(ionic.Platform.isIOS()){
                                    element.triggerHandler('click');
                                }
                            });

                        });
                    }

                }

            }
        }
    };

    directive.$inject = ['$parse','$log'];
    return directive;
});